<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col>
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-input
              v-model="query.blurry"
              clearable
              size="small"
              placeholder="输入名称或者邮箱搜索"
              style="width: 200px;"
              class="filter-item"
              @keyup.enter.native="crud.toQuery"
            />
            <el-date-picker
              v-model="query.createTime"
              :default-time="['00:00:00','23:59:59']"
              type="daterange"
              range-separator=":"
              size="small"
              class="date-item"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
            <el-select
              v-model="query.enabled"
              clearable
              size="small"
              placeholder="状态"
              class="filter-item"
              style="width: 90px"
              @change="crud.toQuery"
            >
              <!-- <el-option
                v-for="item in enabledTypeOptions"
                :key="item.key"
                :label="item.display_name"
                :value="item.key"
              />-->
            </el-select>
            <rrOperation :crud="crud" />
          </div>
          <crudOperation show />
        </div>
        <editUser ref="form3" @torefresh="torefresh" />
        <!--表单渲染-->
        <el-dialog
          append-to-body
          :close-on-click-modal="false"
          :before-close="crud.cancelCU"
          :visible.sync="crud.status.cu > 0"
          :title="crud.status.title"
          width="570px"
        >
          <el-form ref="form" :inline="true" :model="form" size="small" label-width="100px">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="form.userName" style="width:350px" />
            </el-form-item>
            <el-form-item label="用户密码" prop="userPassword">
              <el-input v-model="form.userPassword" style="width:350px" type="password" />
            </el-form-item>
            <el-form-item
              style="margin-bottom: 0;"
              label="用户角色"
              prop="roleList"
              label-width="100px"
            >
              <el-select
                v-model="form.roleList"
                style="width: 350px"
                multiple
                 value-key="id"
                placeholder="请选择"
                @remove-tag="deleteTag"
                @change="changeRole"
              >
                <el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.cu === 2" type="primary" @click="saveUser">确认</el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table
          ref="table"
          v-loading="crud.loading"
          :data="crud.data"
          style="width: 100%;"
          @selection-change="crud.selectionChangeHandler"
        >
          <el-table-column :selectable="checkboxT" type="selection" />
          <el-table-column
            v-if="columns.visible('id')"
            :show-overflow-tooltip="true"
            prop="id"
            label="用户编号"
          />
          <el-table-column
            v-if="columns.visible('userName')"
            :show-overflow-tooltip="true"
            prop="userName"
            label="用户名"
          />
          <el-table-column
            v-if="columns.visible('createTime')"
            :show-overflow-tooltip="true"
            prop="createTime"
            label="创建日期"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columns.visible('lastLoginTime')"
            :show-overflow-tooltip="true"
            prop="lastLoginTime"
            label="上次登录时间"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.lastLoginTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="editUser(scope.row)">用户编辑</el-button>
              <el-popover :ref="scope.row.id" placement="top" width="180">
                <p>确定删除本条数据吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button
                    size="mini"
                    type="text"
                    @click="$refs[scope.row.id].doClose()"
                  >取消</el-button>
                  <el-button
                    :loading="delLoading"
                    type="primary"
                    size="mini"
                    @click="subDelete(scope.row.id)"
                  >确定</el-button>
                </div>
                <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import initData from "@/mixins/crud";
import { del, crudUser, add } from "@/api/system/user";
import { isvalidPhone } from "@/utils/validate";
import { getAll } from "@/api/system/role";
import { getAllJob } from "@/api/system/job";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import editUser from "./edit";
import pagination from "@crud/Pagination";
import Treeselect from "@riophae/vue-treeselect";
import { mapGetters } from "vuex";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Cookies from "js-cookie";

let userRoles = [];
// crud交由presenter持有
const defaultCrud = CRUD({
  title: "用户",
  url: "api/users/userList",
  crudMethod: { ...crudUser },
});
const defaultForm = {
  userName: null,
  userPassword: 123456,
  shopId: null,
  createTime: null,
  lastLoginTime: null,
  roleList: [],
};
export default {
  name: "User",
  components: { crudOperation, rrOperation, udOperation, editUser, pagination },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],

  data() {
    return {
      height: document.documentElement.clientHeight - 180 + "px;",
      roleList: [],
      defaultProps: { children: "children", label: "name" },
      delLoading: false,
      enabledTypeOptions: [
        { key: "true", display_name: "激活" },
        { key: "false", display_name: "锁定" },
      ],
    };
  },
  computed: {
    ...mapGetters(["user"]),
  },
  created() {
    this.$nextTick(() => {
      this.crud.toQuery();
      this.crud.msg.add = "新增成功，默认密码：123456";
    });
  },
  mounted: function () {
    const that = this;
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + "px;";
    };
  },
  methods: {
    torefresh(el) {
      this.$nextTick(() => {
        this.crud.toQuery();
      });
    },
    changeRole(value) {
      userRoles = [];
      console.log(value,"value")
      value.forEach(function (data, index) {
        //const role = { id: data };
        userRoles.push(data);
      });
    },
    [CRUD.HOOK.afterAddError](crud) {
      this.afterErrorMethod(crud);
    },
    [CRUD.HOOK.afterEditError](crud) {
      this.afterErrorMethod(crud);
    },
    afterErrorMethod(crud) {
      // 恢复select
      const initRoles = [];
      userRoles.forEach(function (role, index) {
        initRoles.push(role);
      });
      crud.form.roleList = initRoles
      //crud.form.roleList = userRoles;
    },
    deleteTag(value) {
      userRoles.forEach(function (data, index) {
        if (data.id === value.id) {
          userRoles.splice(index, value);
        }
      });
    },
    subDelete(id) {
      this.delLoading = true;
      del(id)
        .then((res) => {
          this.delLoading = false;
          this.$refs[id].doClose();
          this.crud.toQuery();
          this.$notify({
            title: "删除成功",
            type: "success",
            duration: 2500,
          });
        })
        .catch((err) => {
          this.delLoading = false;
          this.$refs[id].doClose();
          console.log(err.response.data.message);
        });
    },
    saveUser() {
      this.loading = true;
      this.form.shopId = Cookies.get("shopId");
     form.roleList = JSON.parse(JSON.stringify(userRoles))
      console.log("this.crud", (this.crud.status.add = 0));
      console.log(this.form,"======")
      add(this.form)
        .then((res) => {
          this.resetForm();
          this.$notify({
            title: "添加成功",
            type: "success",
            duration: 2500,
          });
          this.crud.toQuery();
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
        });
    },
    editUser(data) {
      const _this = this.$refs.form3;
      let roleNames = [];
      _this.form = {
        id: data.id,
        userName: data.userName,
        userPassword: data.userPassword,
        shopId: data.shopId,
        shopName: data.shopName,
        createTime: data.createTime,
        createId: data.createId,
        updateId: data.updateId,
        updateTime: data.updateTime,
        isDelete: data.isDelete,
        lastLoginTime: data.lastLoginTime,
        bak2: data.bak2,
        bak1: data.bak1,
        roleList: data.roleList,
        roleNames: ''
      };
      getAll()
        .then((res) => {
          _this.form.roleNames = res.data;
          console.log(_this.form, "data");
        })
        .catch(() => {});
      _this.dialog = true;
    },
    beforeInit() {
      this.url = "api/users/userList";
      return true;
    },
    deleteTag(value) {
      userRoles.forEach(function (data, index) {
        if (data.id === value) {
          userRoles.splice(index, value);
        }
      });
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getRoles();
      form.enabled = true;
    },
    // 打开编辑弹窗前做的操作
    [CRUD.HOOK.beforeToEdit](crud, form) {
      userRoles = [];
      const roleList = [];
      form.roleList.forEach(function (role, index) {
        roleList.push(role.id);
        // 初始化编辑时候的角色
        const rol = { id: role.id };
        userRoles.push(rol);
      });
      form.roleList = roleList;
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (this.roleList.length === 0) {
        this.$message({
          message: "角色不能为空",
          type: "warning",
        });
        return false;
      }
      // crud.form.roleList = userRoles;
      return true;
    },
    //改变状态
    changeEnabled(data, val) {
      this.$confirm(
        '此操作将 "' +
          this.dict.label.user_status[val] +
          '" ' +
          data.username +
          ", 是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          crudUser
            .edit(data)
            .then((res) => {
              this.crud.notify(
                this.dict.label.user_status[val] + "成功",
                CRUD.NOTIFICATION_TYPE.SUCCESS
              );
            })
            .catch(() => {
              data.enabled = !data.enabled;
            });
        })
        .catch(() => {
          data.enabled = !data.enabled;
        });
    },
    //获取弹窗内角色数据
    getRoles() {
      getAll()
        .then((res) => {
          console.log(res.data,"res.data")
          this.roleList = res.data;
        })
        .catch(() => {});
    },
    // 点击部门搜索对应的岗位
    selectFun(node, instanceId) {
      this.getJobs(node.id);
      this.form.job.id = null;
    },
    // 获取权限级别
    getRoleLevel() {
      getLevel()
        .then((res) => {
          this.level = res.level;
        })
        .catch(() => {});
    },
    resetForm() {
      this.dialog = false;
      this.$refs["form"].resetFields();
      this.form = {
        id: "",
        userName: "",
        userPassword: "123456",
        shopId: "",
        createTime: "",
        createId: "",
        updateId: "",
        updateTime: "",
        isDelete: "",
        lastLoginTime: "",
        bak2: "",
        bak1: "",
      };
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.id;
    },
  },
};
</script>

<style scoped>
</style>
